using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework.Storage;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ProjectCastamere
{
    /// <summary>
    /// represents all the save game information for a particular player's save game
    /// </summary>
    //[Serializable]
    public class Profile
    {
        // string used to uniquely identify the profile (usually players name)
        String profileName;

        // list of medals they have gained
        List<Medal> medals;

        // number of enemies defeated
        int numEnemiesKilled;

        // number of towers placed
        int towersPlaced;

        public void Save(StorageDevice device)
        {
            IAsyncResult result = device.BeginOpenContainer("CastamereStorage", null, null);

            // wait for the WaitHandle to become signalled
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // close the wait handle
            result.AsyncWaitHandle.Close();

            string filename = "savegame_" + profileName + ".profile";

            // check to see if this save file already exists
            if (container.FileExists(filename))
            {
                // delete the previous save
                container.DeleteFile(filename);
            }

            // create the stream object
            Stream stream = container.CreateFile(filename);

            XmlSerializer serializer = new XmlSerializer(typeof(Profile));

            serializer.Serialize(stream, this);

            stream.Close();
            container.Dispose();
        }

        public static Profile Load(StorageDevice device, String profileName)
        {
            IAsyncResult result = device.BeginOpenContainer("CastamereStorage", null, null);

            // wait for the WaitHandle to become signalled
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // close the wait handle
            result.AsyncWaitHandle.Close();

            string filename = "savegame_" + profileName + ".profile";

            if (container.FileExists(filename))
            {
                container.Dispose();
                return null;
            }

            // open the input stream
            Stream stream = container.OpenFile(filename, FileMode.Open);

            XmlSerializer serializer = new XmlSerializer(typeof(Profile));

            Profile p = (Profile)serializer.Deserialize(stream);

            // close the file stream
            stream.Close();

            container.Dispose();

            return p;
        }
    }
}
